
L.SelectTool = L.Tool.extend({

  enable: function(editor) {
    this._elements = [];
    L.Tool.prototype.enable.call(this, editor);
    this.name = "select_tool";
    this.set = null;

    // Drawing state
    this._drawing = false;
    this._c = null;
    this._x = 0;
    this._y = 0;
    this._w = 0;
    this._h = 0;
  },


  onDragstartElement: function(element, event){
    var self = this;

    if(!element.selected){
      element.selected = true;
      this._elements.push(element);
    }

    this._drawSelection();
    event.stopPropagation();
  },

  onDragmoveElement: function(element, event){
    event.stopPropagation();
  },

  onDragendElement: function(element, event){
    event.stopPropagation();
  },


  onDragstartCanvas: function(canvas, event){
    //console.log("start");

    this._drawing = true;
    this._movingAtOnce = false;
    var pos = canvas.getPos(event);

    this._c = canvas.getRaphael().rect();
    this._x = pos.x;
    this._y = pos.y;
    this._dx = 0;
    this._dy = 0;

    this._c.attr({ 
      'x':this._x,
      'y':this._y,
      'width':2,
      'height':2,
      'fill': '#B6C4F2',
      'stroke': '#8DA4F0',
      'stroke-width':2,        
      'fill-opacity': 0.1,
    });
    
    //console.log("this._elements.length:"+ this._elements.length);
    if(this._elements.length == 0){
      var box = this._c.getBBox();
      var inter = this._findIntersectedElements(canvas, box, true);
      //console.log("inter:"+ inter);
      if (inter) {
        this._drawSelection();
        this._movingAtOnce = true;
        this._c.remove();  
        this._c = null;
      }
    }
  },

  onDragmoveCanvas: function(canvas, event) {   
    //console.log("drag");
    if (this._drawing == true) {
      var pos = canvas.getPos(event);
      var x = this._x;
      var y = this._y;
      var dx = (pos.x-x);
      var dy = (pos.y-y);
      var signx = 1;
      var signy = 1;
      if(dx<0){
        x=pos.x;
        dx=-dx;
        signx = -1;
      }
      if(dy<0){
        y=pos.y;
        dy=-dy;
        signy = -1;
      }

      this._dx = dx;
      this._dy = dy;


      if (this._movingAtOnce) {
    	  if( Skt.editingEnabled ) {
				var ft = this._set.ft;
				ft.attrs.translate = { x: dx*signx, y: dy*signy };
				ft.apply();
				//console.log("this._dx:"+this._dx+ " this._dy:"+this._dx)
    	  }
      } else {
        this._c.attr({x:x, y:y, width:dx, height:dy});
      }
    }
  },

  onDragendCanvas: function(canvas, event){
    //console.log("end");
    if(this._drawing == true){
      this._drawing = false;
      if (this._movingAtOnce) {
        if ( this._dx > 10 || this._dy > 10 ) {
            this.emptySelection();
        }else{
          //this._checkText();
        }
        return;
      } else {
        if (this._c == null)
          return;
        var box = this._c.getBBox();
        this._c.remove();  
        this._c = null;
        //var boxtext = Raphael.format("M{0},{1}h{2}v{3}h{4}v{5}", box.x, box.y, box.width, box.height, -box.width, -box.height);
        //var boxpath = canvas.getRaphael().path(boxtext);
        //console.log(boxpath);
        //boxpath.remove();
        var just_one = false;
        //se verifica si solo se realizo un toque o se intenta arrastrar inmediatamente
        if ( box.width < 10 && box.height < 10 ) {
          //if(self._elements.length> 0 ){
            //en caso de tener mas elementos tomados el toque los deselecciona (para tomar mas de uno deben cubrirse sin toque)
            this.emptySelection();
          //}
          // un toque solo selecciona un elemento
          just_one = true;
        }
        var found = this._findIntersectedElements(canvas, box, just_one);
      }

      if(!found){
        this.emptySelection();
        return;
      }

      this._drawSelection();
      //this._checkText();
    }
  },

  _findIntersectedElements: function(canvas, box, just_one){
    var self = this;
    var found = false;
    canvas.eachElement(function(el){
      //console.log("el");console.log(el);
      var inter = el.intersectWithBox(box);
      //var inter = el.intersectWithPath(boxpath);
      if(inter && $.inArray(el, self._elements) == -1 && (just_one == false || found == false)){
        //console.log("type:"+el._attrs.type);
        self._elements.push(el);
        el.selected = true;
        el.drawBorder();
      }
      if(inter){
        found = true;
      }
    });
    return found;
  },

  disable: function(editor){
    this.emptySelection();
  },

  getSelection: function(){
    var elements = this._elements;
    var selection = [];
    
    for(var i=0, n=elements.length; i<n; i++){
      selection[i] = elements[i];
    }

    return selection;
  },

  setSelection: function(selection){
    this.emptySelection();

    if(selection && selection.length){
      for(var i=0, n=selection.length; i<n; i++){
        var el = selection[i];
        this._elements.push(el);
        el.selected = true;
        el.drawBorder();
      }

      this._drawSelection();  
    }
  },

  emptySelection: function(){
    var self = this;
    var elements = this._elements;
    var map = {};

    for(var i=0, n=elements.length; i<n; i++){
      var el = elements[i];
      map[el.id] = el;
      el.selected = false;
      el.removeBorder();
    }

    if(this._set){
      this._set.forEach(function(raphaelElement){
        var attrs = raphaelElement.attr(['stroke','fill','transform']);
        //if (raphaelElement.type == "text") {
        //  attrs['text'] = raphaelElement.attr(['text']).text;
        //}
        attrs['id']= raphaelElement.data("elementId");
        //console.log('raphaelElement');console.log(raphaelElement);
        //console.log('attrs');console.log(attrs);
        if(attrs.id && typeof attrs.id == "string"){
          self._canvas.updateElement(attrs.id, attrs);
        }
        return true;
      });

      if(this._edit_button){
        this._edit_button.remove();
      }
      this._set.ft.unplug();
      this._set.clear();
      this._set = null;
      this._editor.updateMiniview(this._canvas);
    }
      
    this._elements = [];
  },

  _drawSelection: function(){

    if(this._set){
      this._set.ft.unplug();
    }

    var raphael = this._canvas.getRaphael();
    var set = raphael.set();
    
    var rotable = true;
    var scalable = true;
    var elements = this._elements;
    //console.log("elements");
    //console.log(elements);
    for(var i=0, n=elements.length; i<n; i++){
      var elems = elements[i].getRaphaelElement();
      //console.log("elems");
      //console.log(elems);
      set.push.apply(set, elems);
      if(rotable && !elements[i].rotable()){
        rotable = false;
      }
      if(scalable && !elements[i].scalable()){
        scalable = false;
      }
    }

    var options = { 
      attrs: { fill: '#fff', stroke: '#8DA4F0'},
      size: 10,
      draw: ['bbox'],
      distance: 30,
      drag: false,
      rotate: false,
      scale: false
    };
    
    if ( Skt.editingEnabled ) {
    	options['drag'] = ['self'];
        if (rotable)
            options['rotate'] = ['axisY'];
        if (scalable)
            options['scale'] = ['bboxCorners', 'bboxSides'];
    }


    //alert("rotable:" + rotable);
    //console.log("set");
    //console.log(set);
    set.ft = raphael.freeTransform(set, options);

    this._set = set;
  },

  _checkText: function(){
    var self = this;
    if(this._elements.length == 1){
      var elem = this._elements[0]._element;
      this._set.push.apply(this._set, [elem]);
      if(elem['type'] == 'text'){
        // mostrar boton editar
        var x = $(elem[0]).offset().left;
        var y = $(elem[0]).offset().top;
        var edit_button = $('<div id="editTextButton"><a class="btn" href="#"><i class="icon-edit"></i></a></div>');
        this._edit_button = edit_button;
        $(document.body).append(edit_button);
        edit_button
          .css({
            'position':"absolute",
            'width':20, 'height':20,
            'top':y-43, 'left':x,
          })
          .click(function(){
            edit_button.remove();
            // mostrar input
            console.log('elem[0]');console.log(elem[0]);
            var text_old = elem.attrs['text'];
            var color = elem.attrs['fill'];
            var input = $("<textarea id='inputElement'>"+text_old+"</textarea>");
            $(document.body).append(input);
            input
              .css({
                position:"absolute",
                "width":120, "height":60,
                top:y+0, left:x+0,
                'font-size': '18pt',
                'color': color
              })
              .resizable({ minHeight: 30, minWidth: 60 })
              .focus()
              .blur(function(){
                var text = $(this).val();
                if(text.length > 0 && text != text_old){
                  elem.attrs['text'] = text;
                  var attrs = elem.attr(['text']);
                  attrs['id']= elem.id;
                  if(attrs.id && typeof attrs.id == "string"){
                    self._canvas.updateElement(attrs.id, attrs);
                  }
                }
                $(this).remove();
              });
            });
      }
     
      console.log(this._elements[0]);
    }
  }

});
